<template>
  <div class="d_picker">
    <van-field
      is-link
      readonly
      name="picker"
      label="选择器"
      placeholder="请选择"
      v-bind="$attrs"
      input-align="right"
      @click="showPicker = true"
      :model-value="displayValue"
    />

    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker
        :columns="list"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";

const props = defineProps({
  list: { type: Array, default: () => [] },
  modelValue: { type: [String, Number], default: "" }, // 接收 modelValue prop
});

const emit = defineEmits(["update:modelValue"]);
const showPicker = ref(false);

// 可选：如果需要显示文本而不是值，需要额外处理
const displayValue = computed(() => {
  if (!props.modelValue) return "";

  // 在列表中查找对应的文本
  const selectedItem = props.list.find(
    (item) => item.value === props.modelValue
  );

  return selectedItem ? selectedItem.text : "";
});

const onConfirm = ({ selectedOptions }) => {
  const selected = selectedOptions[0];
  if (selected) {
    emit("update:modelValue", selected.value);
  }
  showPicker.value = false;
};
</script>